import requests
from common import yaml_util
from common import Log
from common import config_util
from urllib.parse import urljoin
import traceback

#封装的request类，用于接收请求参数发送请求，返回response
class RequestsUtil:
    def __init__(self):
        self.session = requests.Session()

    def all_send_request(self, method, url, headers=None, data=None):
        if method.lower() == 'get':
            res = self.session.get(url, headers=headers, params=data)
        else:
            res = self.session.request(method, url, headers=headers, json=data)
        return res

requests_util_instance = RequestsUtil()

#封装类，进行调用request类进行请求，获得response后进行断言，打印日志操作
class TestUtil:
    logger = Log.logger
    def __init__(self):
        self.util_instance = RequestsUtil()
        self.domain_name = config_util.Config('test2')

    def send_request_and_assert(self, case, yaml_file):
        read_yaml = yaml_util.Yaml_Util().read_testcase_yaml(yaml_file)
        try:
            res = self.util_instance.all_send_request(
                method=case['method'],
                url=urljoin(self.domain_name.base_url, case['url']),
                headers=read_yaml['header'],
                data=case['data']
            )
            print(res.url)
            if 'expected' in case:
                # 断言状态码
                assert res.status_code == case['expected']['status_code']
                # 断言响应 JSON
                if 'json' in case['expected']:
                    assert res.json()['code'] == case['expected']['json']['code']
                    self.logger.info(f"------------------------")
                    self.logger.info(f"测试用例-{case['name']} 通过")
                    self.logger.info(f"------------------------")
                    return res
                else:
                    self.logger.info(f"测试用例 {case['name']} 缺失断言内容")
                    return res

            else:
                return res
        except AssertionError as e:
            self.logger.error(f"用例-{case['name']}:{e}失败")
            self.logger.error(f"期望请求结果: {case['expected']}")
            self.logger.error(f"实际请求结果: {res.json()}")
            self.logger.error(f"故障节点".join(traceback.format_exception(None, e, e.__traceback__)))
            raise
        except RuntimeError as e:
            self.logger.error(f"用例 {case['name']} 超时: {e}")
            raise

#TestUtil创建的类实例，提供给其他方法调用
Reqs = TestUtil()


if __name__ == '__main__':
    pass
